<template>
  <!-- 车辆库存 > 车辆入库 -->
  <div>
    <TopFilter
      ref="formpanel"
      :list="topFilterList"
      :cols="3"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="true"
      :onColumnsChange="columns => this.columns = columns"
      :onRowSelectChange="getSelectData"
      :onSyncTableData="tableDataChange"
    >
      <template slot="controls">
        <el-button size="small" type="primary"  @click="addHandleBtn">批量入库</el-button>
        <el-button size="small" type="primary" :loading="exportLoading"  @click="exportFileBtn">导出</el-button>
      </template>
    </FilterTable>
  </div>
</template>
<script>
import { inStock, qryVehicleCheckPage, qryVehicleCheckExcel } from '@/api/vehicle/stockmanage/stockIn';
import { dictionary } from '@/utils/dictMixin';
import { notifyAction } from '@/utils';
import { exportExcelFile } from '@/utils/index';
import moment from 'moment'
export default {
  name: 'StockIn',
  mixins: [dictionary],
  data () {
    return {
      topFilterList: this.createTopFilters(), // 查询区条件
      columns: this.createTableColumns(), // 列表区数据
      fetchApi: qryVehicleCheckPage, // 条件查询接口
      fetchParams: {}, // 查询参数
      theSelects: [],
      exportLoading: false
    }
  },
  created () {
  },
  mounted () {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    changeHandle (val){
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    createTopFilters () {
      return [
        {
          type: 'SELECT',
          label: '业务类型',
          fieldName: 'inDeliveryType',
          placeholder: '请选择...',
          itemList: this.createDictList('1317')
        },
        {
          type: 'INPUT',
          label: '销售订单号',
          fieldName: 'viNo',
          placeholder: '请输入...'
        },
        {
          type: 'RANGE_DATE',
          label: '入库日期',
          fieldName: 'latestStockInDateStart|latestStockInDateEnd',
          placeholder: '请选择...'
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请输入...'
        }
      ]
    },
    createTableColumns () {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={props.row.isInOutStock === 10041002 ? false : true} onClick={() => props.row.isInOutStock === 10041001 ? this.detailFun(props.row) : ''}>
                  入库
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '业务类型',
          dataIndex: 'inDeliveryType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1317'),
          render: props => {
            return <span> { this.preDictHandler(props.row.inDeliveryType,'1317')} </span>
          }
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '质损状态',
          dataIndex: 'trafficMarStatus',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1040'),
          render: props => {
            return <span> { this.preDictHandler(props.row.trafficMarStatus,'1040')} </span>
          }
        },
        {
          title: '入库单号',
          dataIndex: 'inOutStockNo',
          width: 140,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '入库日期',
          dataIndex: 'latestStockInDate',
          width: 140,
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span> { this.preDateHandler(props.row.latestStockInDate) } </span>
          }
        },
        {
          title: '销售订单号',
          dataIndex: 'viNo',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '产品代码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '产品名称',
          dataIndex: 'productName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
      ]
    },
    // 被选择数据
    getSelectData (val) {
      this.theSelects = val
    },
    // 禁用行checkbox选中
    tableDataChange (data, isFirst) {
      if (isFirst) {
        let disabledSelect = data.filter(row => row.isInOutStock !== 10041001)
        this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT(disabledSelect)
      }
    },
    // 批量入库
    addHandleBtn () {
      // params: Array[]
      let isCan = this.theSelects.some(x => x.inOutStockId == null || x.inOutStockId == '');
      if (isCan) {
        notifyAction('存在一条坏数据，请联系管理员','error');
        return
      }
      let params = this.theSelects.map(x => x.inOutStockId);
      let msg = [['批量入库成功'],['批量入库失败','error']];
      params && params.length > 0 ? this.putInStorage( {'inOutStockIdList': params}, msg) : notifyAction('请选选择数据','error');
    },
    // 单个入库
    detailFun (val, deFineError=[['请选择一条数据','error'],['这是一条坏数据，请联系管理员','error']]) {
      let msgError = ''
      if (!val.inOutStockId && !theSelects.length) {
        if (!theSelects.length) {
          msgError = deFineError[0]
        } else if (!val.inOutStockId) {
          msgError = deFineError[1]
        }
        notifyAction(...msgError);
        return
      }
      let params = {'inOutStockIdList':[val.inOutStockId]}
      this.putInStorage(params)
    },
    // 列表入库事件
    putInStorage(params,defineMsg=[['入库成功'],['入库失败','error']]){
      let msg = ''
      inStock(params).then(res => {
        if (res.success) {
          msg = defineMsg[0];
          // 延迟刷新
          setTimeout(()=>{
            this.fetchParams = { ...this.fetchParams };
          }, 0);
        } else {
          msg = defineMsg[1];
        }
        notifyAction(...msg);
      });
    },
    // 导出
    exportFileBtn () {
      this.$refs.formpanel.SUBMIT_FORM();
      this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
	        confirmButtonText: '下载',
	        cancelButtonText: '取消',
	        type: 'warning'
	      }).then(() => {
          qryVehicleCheckExcel(this.fetchParams).then( response => {
            exportExcelFile(response.data, "车辆入库");
            this.exportLoading = false;
          }).catch( err => {
            console.log(err)
          })
	      }).catch(() => {
	        this.$message({
	          type: 'info',
	          message: '已取消'
	        });
	      });
    },
    // 字典数据使用前预处理
    preDictHandler(val, code){
      let resultText = val && String.prototype.includes.call(val, code) ? this.createDictText(val, code) : val;
      return resultText;
    },
    // 日期预处理
    preDateHandler(val, formatCode='YYYY-MM-DD HH:mm:ss') {
      let resultDate = val ? moment(Number(val)).format(formatCode) : val;
      return resultDate;
    },
  }
}
</script>
<style lang="less" scoped>
</style>
